package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: 爱学Java 不想秃头的 KK
 * @date: 2023/7/27 8:25
 * @version: 1.0
 * @Created with IntelliJ IDEA.
 * @Description:
 */


@Slf4j
@RestController
@ResponseBody
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishService dishService;
    @Autowired
    private CategoryService categoryService;


    /**
     * 保存菜品信息
     *
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        dishService.saveWithFlavour(dishDto);
        return R.success("菜品添加成功！");
    }


    /**
     * 菜品分页条件查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        Page pageInfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(null != name, Dish::getName, name);
        //已经逻辑删除的不再展示
        queryWrapper.eq(Dish::getIsDeleted, 0);
        queryWrapper.orderByDesc(Dish::getCreateTime);
        dishService.page(pageInfo, queryWrapper);

        //为了满足前端页面显示，否则分类名称无法显示，只传过去了分类id
        Page<DishDto> dishDtoPage = new Page<>();
        //把pageInfo的值拷贝到dishDtoPage，同时忽略pageInfo中的records
        BeanUtils.copyProperties(pageInfo, dishDtoPage, "records");
        List<Dish> records = pageInfo.getRecords();

        //利用Stream流查询菜品名称
        List<DishDto> list = records.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            //前面的拷贝把records排除，现在拷贝是为了在dishDto中保存records拿到categoryId
            BeanUtils.copyProperties(item, dishDto);
            Long categoryId = dishDto.getCategoryId();
            Category category = categoryService.getById(categoryId);
            //将分类名称设置到dishDto中
            dishDto.setCategoryName(category.getName());
            return dishDto;
        }).collect(Collectors.toList());

        dishDtoPage.setRecords(list);

        return R.success(dishDtoPage);
    }

    /**
     * 根据id查询菜品信息和口味信息
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> getDish(@PathVariable Long id) {
        DishDto dishWithFlavour = dishService.getDishWithFlavour(id);
        return R.success(dishWithFlavour);
    }


    /**
     * 修改菜品信息
     *
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> updateInfo(@RequestBody DishDto dishDto) {
        dishService.updateWithFlavour(dishDto);
        return R.success("菜品信息修改成功！");
    }


    /**
     * 起售或停售菜品信息，支持批量操作
     *
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public R<String> updateStatus(@PathVariable int status, @RequestParam("ids") List<Long> ids) {
        if (ids.isEmpty()) {
            return R.error("请至少选择一个菜品！");
        }
        for (Long id : ids) {
            Dish dish = dishService.getById(id);
            dish.setStatus(status);
            dishService.updateById(dish);
        }
        return R.success("菜品信息更改成功！");
    }


    /**
     * 逻辑删除菜品，支持批量操作
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> deleteDish(@RequestParam("ids") List<Long> ids) {
        if (ids.isEmpty()) {
            return R.error("请至少选择一个菜品！");
        }
        for (Long id : ids) {
            Dish dish = dishService.getById(id);
            dish.setIsDeleted(1);
            dishService.updateById(dish);
        }
        return R.success("菜品删除成功！");
    }


    /**
     * 根据条件查询菜品信息
     *
     * @param dish
     * @return
     */
    @GetMapping("/list")
    public R<List<Dish>> list(Dish dish) {
        //构造查询条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<Dish>();
        queryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId())
                    .eq(Dish::getStatus, 1L)
                    .orderByAsc(Dish::getSort)
                    .orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(queryWrapper);

        return R.success(list);
    }



}
